package pers.ree.demo.concurrent.lock;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReentrantReadWriteLockDemo {

    private static ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    private static ReentrantReadWriteLock.ReadLock readLock = readWriteLock.readLock();

    private static ReentrantReadWriteLock.WriteLock writeLock = readWriteLock.writeLock();

    private static List<Integer> numList;

    static {
        numList = new ArrayList<>();

        for (int i=0; i<10; i++) {
            numList.add(i);
        }
    }

    public static void read() {
        readLock.lock();

        System.out.println(Thread.currentThread().getName() + "加读锁");

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        for (Integer i: numList) {
            System.out.println("读"+i);
        }

        readLock.unlock();
    }

    public static void write() {
        writeLock.lock();

        System.out.println(Thread.currentThread().getName()+"加写锁");

        try {
            Thread.sleep(6000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        for (int i=1000; i<1005; i++) {
            numList.add(i);
            System.out.println("写入"+i);
        }

        writeLock.unlock();
    }

    public static void main(String[] args) {
//        ReentrantReadWriteLock rrwLock = new ReentrantReadWriteLock();
//
//        ReentrantReadWriteLock.ReadLock readLock = rrwLock.readLock();
//
//        readLock.lock();
//
//        readLock.unlock();

        new Thread(()->read()).start();

        new Thread(()->write()).start();

        new Thread(()->read()).start();
    }
}
